package fr.reseau.echec;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FichierReseau {

	public final static int NUM_PORT = 2014;
	public final static int FILE_SIZE = 99999;

	public static void envoieFichier(String fichier) throws IOException {
		
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		OutputStream os = null;
		ServerSocket server = null;
		Socket socket = null;
		
		try {
			server = new ServerSocket(NUM_PORT);
			while (true) {
				try {
					socket = server.accept();
					File file = new File (fichier);
					byte [] tabByte  = new byte [(int)file.length()];
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					bis.read(tabByte,0,tabByte.length);
					os = socket.getOutputStream();
					os.write(tabByte,0,tabByte.length);
					os.flush();
				}
				finally {
					if (bis != null)
						bis.close();
					if (os != null)
						os.close();
					if (socket!=null)
						socket.close();
				}
			}
		}
		finally {
			if (server != null)
				server.close();
		}
	}
	
	public static void RecevoirFichier(String adrIP, String fichier) throws IOException {

		int byteLu;
		int courant = 0;
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		Socket socket = null;
		
		try {
			socket = new Socket(adrIP, NUM_PORT);
			byte [] tabByte  = new byte [FILE_SIZE];
			InputStream inputS = socket.getInputStream();
			fos = new FileOutputStream(fichier);
			bos = new BufferedOutputStream(fos);
			byteLu = inputS.read(tabByte,0,tabByte.length);
			courant = byteLu;

			do {
				byteLu = inputS.read(tabByte, courant, (tabByte.length)-courant);
				if (byteLu >= 0)
					courant += byteLu;
			} while(byteLu > -1);
			bos.write(tabByte, 0 , courant);
			bos.flush();
		}
		
		finally {
			if (fos != null)
				fos.close();
			if (bos != null)
				bos.close();
			if (socket != null)
				socket.close();
		}
	}
}